//
//  UserAccountViewModel.swift
//  sinaweibo
//
//  Created by mac on 15/11/11.
//  Copyright © 2015年 mac. All rights reserved.
//

import UIKit
import AFNetworking

class UserAccountViewModel: NSObject {
    
    //增加userAccount属性
    var account:UserAccount?
    
    var userLogin: Bool {
        return token != nil
    }
    
    var token: String? {
        return account?.access_token
    }
    //用户名
    var userName: String? {
        return account?.name
    }
    //用户头像URL
    var headURL: NSURL? {
        return NSURL(string: (account?.avatar_large ?? ""))
    }
    
    override init() {
        account = UserAccount.loadAccount()
    }
    
    func loadAccessToken(code: String, finished: (error: NSError?) -> ()) {
        
        let urlString = "https://api.weibo.com/oauth2/access_token"
        let parameters = ["client_id":client_id, "client_secret":client_secret, "grant_type":"authorization_code", "code":code, "redirect_uri":redirect_uri]
        
        NetworkTools.sharedTools.requestJsonDict(.POST, urlString: urlString, parameters: parameters) { (result, error) -> () in
            if error != nil {
                //如果error 有值时记得return 否则会报错
//                print("-------------")
//                print(error)
                finished(error: error)
                return
            }
             
            let account = UserAccount(dict: result!)
            
            self.loadUserInfo(account, finished: finished)
            
//            finished(error: nil)
        }
    }
    
    private func loadUserInfo(account: UserAccount, finished: (error: NSError?) -> ()) {
        
        let urlString = "https://api.weibo.com/2/users/show.json"
        let parameters = ["access_token": account.access_token!, "uid": account.uid!]
        NetworkTools.sharedTools.requestJsonDict(.GET, urlString: urlString, parameters: parameters) { (result, error) -> () in
            
            if error != nil {
                finished(error: error)
                return
            }
//            print(result)
            account.name = result!["name"] as? String
            account.avatar_large = result!["avatar_large"] as? String
            
            //将用户信息保存到沙盒中
            account.saveAccount()
            
            finished(error: nil)
        }
    }
}
